﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Pku.BookStore.Web.Controllers
{
    //[ManageAuthorizeAttribute]
    public class AdminController : BaseController
    {

        // GET: /Admin/

        #region 首页

        public ActionResult Index()
        {
            IServices.IUserServices userDal = new Services.UserServices();
            IServices.IProductServices productDal = new Services.ProductServices();
            IServices.IOrderFormServices orderformDal = new Services.OrderFormServices();

            ViewBag.UserCount = userDal.GetCount(null);
            ViewBag.ProductCount = productDal.GetCount(new Model.ProductParam());
            ViewBag.OrderCount = orderformDal.GetCount(new Model.OrderFormParam());

            //取最新5个订单
            Model.OrderFormParam orderParam = new Model.OrderFormParam();
            orderParam.PageNo = 1;
            orderParam.PageRow = 5;
            orderParam.BeginDate = Utility.CommonHelper.DataTimeMinValue;
            orderParam.EndDate = Utility.CommonHelper.DataTimeMaxValue;
            orderParam.UserName = string.Empty;
            var orderList = orderformDal.Search(orderParam);

            //新注册用户 5个
            Model.UserParam userParam = new Model.UserParam();
            userParam.BeginDate = Utility.CommonHelper.DataTimeMinValue;
            userParam.EndDate = Utility.CommonHelper.DataTimeMaxValue;
            userParam.PageNo = 1;
            userParam.PageRow = 5;
            userParam.UserName = string.Empty;
            var userList = userDal.Search(userParam);

            IDictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("OrderList", orderList);
            dic.Add("UserList", userList);

            return View(dic);
        }
        #endregion

        #region 登录
        public ActionResult LogOn(string Act)
        {
            if (Act == "LogOut")
            {
                Session["EmployeeID"] = null;
                Session["EmployeeName"] = null;
                Session["LastDate"] = null;
                Session["LastIP"] = null;
                return RedirectToAction("LogOn", "Admin");
            }
            if (Session["EmployeeID"] != null)
            {
                return RedirectToAction("Index", "Admin");
            }
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(Model.EmployeeModel model)
        {
            model.EmployeePass = Utility.EncryptHelper.MD5(model.EmployeePass);
            IServices.IEmployeeServices dalEmplyee = new Services.EmployeeServices();
            var logonResult = dalEmplyee.Login(model);
            if (logonResult != null)
            {
                Session["EmployeeID"] = logonResult.EmployeeID;
                Session["EmployeeName"] = logonResult.EmployeeName;
                Session["LastDate"] = logonResult.LastDate;
                Session["LastIP"] = logonResult.LastIP;
                return RedirectToAction("Index", "Admin");
            }
            else
            {
                ModelState.AddModelError("LoginError", "用户名或密码错误2");
            }
            return View();
        }
        #endregion

        #region 用户管理
        public ActionResult UserList(int? p)
        {
            if (p == null) p = 1;
            IServices.IUserServices userDal = new Services.UserServices();
            ViewBag.UserCount = userDal.GetCount(null);

            //新注册用户 5个
            Model.UserParam userParam = new Model.UserParam();
            userParam.BeginDate = Utility.CommonHelper.DataTimeMinValue;
            userParam.EndDate = Utility.CommonHelper.DataTimeMaxValue;
            userParam.PageNo = Convert.ToInt32(p);
            userParam.PageRow = 10;
            userParam.UserName = string.Empty;
            var userList = userDal.Search(userParam);


            return View(userList);
        }

        public ActionResult UserEdit(int? ID, string Act, Model.UserModel model)
        {
            if (ID == null) ID = 0;
            IServices.IUserServices userDal = new Services.UserServices();
            if (Act == "E")
            {
                model.UserID = Convert.ToInt32(ID);
                if (userDal.Modify(model))
                {
                    ModelState.AddModelError("Info", "操作成功");
                }
                else
                {
                    ModelState.AddModelError("Info", "操作失败请联系管理员");
                }
            }


            var userModel = userDal.GetEntityById(Convert.ToInt32(ID));
            return View(userModel);
        }

        public ActionResult UserEditPass(int? ID, string Act, Model.UserModel model, string UserPassNew, string UserPassNew2)
        {
            if (ID == null) ID = 0;
            IServices.IUserServices userDal = new Services.UserServices();
            if (Act == "E")
            {
                if (UserPassNew != UserPassNew2)
                {
                    ModelState.AddModelError("Info", "两次输入密码不一致，请核查");
                }
                else
                {
                    model.UserPwd = Utility.EncryptHelper.MD5(model.UserPwd);
                    if (userDal.Login(model) == null)
                    {
                        ModelState.AddModelError("Info", "密码不正确，请核查");
                    }
                    else
                    {
                        model.UserPwd = Utility.EncryptHelper.MD5(UserPassNew);
                        model.UserID = Convert.ToInt32(ID);
                        if (userDal.ModifyPass(model))
                        {
                            ModelState.AddModelError("Info", "操作成功");
                        }
                        else
                        {
                            ModelState.AddModelError("Info", "操作失败请联系管理员");
                        }
                    }
                }
            }


            var userModel = userDal.GetEntityById(Convert.ToInt32(ID));
            return View(userModel);
        }
        #endregion

        #region  订单管理
        public ActionResult OrderList(int? p)
        {
            if (p == null) p = 1;
            IServices.IOrderFormServices orderDal = new Services.OrderFormServices();
            ViewBag.OrderCount = orderDal.GetCount(null);

            var param = new Model.OrderFormParam();
            param.BeginDate = Utility.CommonHelper.DataTimeMinValue;
            param.EndDate = Utility.CommonHelper.DataTimeMaxValue;
            param.PageNo = Convert.ToInt32(p);
            param.PageRow = 10;
            var orderList = orderDal.Search(param);


            return View(orderList);
        }

        public ActionResult OrderEdit(int? ID, string Act, Model.OrderFormModel model)
        {
            if (ID == null) ID = 0;
            IServices.IOrderFormServices orderDal = new Services.OrderFormServices();

            if (Act == "E")
            {
                model.OrderID = Convert.ToInt32(ID);
                if (orderDal.ModifyStatus(model))
                {
                    ModelState.AddModelError("Info", "操作成功");
                }
                else
                {
                    ModelState.AddModelError("Info", "操作失败请联系管理员");
                }
            }

            var statusListr = Utility.EnumHelper.GetCachedDictionary(typeof(Utility.EnumUtility.OrderStatus));
            List<SelectListItem> Items = new List<SelectListItem>();
            foreach (var item in statusListr)
            {
                Items.Add(new SelectListItem { Value = item.Key, Text = item.Value });
            }
            ViewBag.statusList = Items;
            var orderModel = orderDal.GetEntityById(Convert.ToInt32(ID));
            return View(orderModel);
        }
        #endregion

        #region 图书分类
        public ActionResult CategoryList(int? p)
        {
            if (p == null) p = 1;

            IServices.ICategoryServices categoryDal = new Services.CategoryServices();
            ViewBag.CategoryCount = categoryDal.GetCount(null);

            var param = new Model.CategoryParam();
            param.PageNo = Convert.ToInt32(p);
            param.PageRow = 10;
            param.Level = 0;
            param.pCatid = 0;
            var categoryList = categoryDal.Search(param);
            return View(categoryList);
        }

        public ActionResult CategoryEdit(int? ID, string Act, Model.CategoryModel model)
        {
            if (ID == null) ID = 0;
            IServices.ICategoryServices categoryDal = new Services.CategoryServices();

            if (Act == "E")
            {
                model.CategoryID = Convert.ToInt32(ID);
                if (!categoryDal.Exist(model.CategoryName))
                {
                    if (categoryDal.Modify(model))
                    {
                        ModelState.AddModelError("Info", "操作成功");
                    }
                    else
                    {
                        ModelState.AddModelError("Info", "操作失败请联系管理员");
                    }
                }
                else
                {
                    ModelState.AddModelError("Info", "分类已经存在，请核查");
                }
            }
            else if (Act == "A")
            {
                if (!categoryDal.Exist(model.CategoryName))
                {
                    if (categoryDal.Add(model) != 0)
                    {
                        ModelState.AddModelError("Info", "操作成功");
                    }
                    else
                    {
                        ModelState.AddModelError("Info", "操作失败请联系管理员");
                    }
                }
                else
                {
                    ModelState.AddModelError("Info", "分类已经存在，请核查");
                }
            }
            else if (Act == "D")
            {
                if (categoryDal.Delete(Convert.ToInt32(ID)))
                {
                    ModelState.AddModelError("Info", "操作成功");
                }
                else
                {
                    ModelState.AddModelError("Info", "操作失败请联系管理员");
                }
                return Redirect("/Admin/CategoryList");
            }

            var categoryModel = categoryDal.GetEntityById(Convert.ToInt32(ID));
            if (categoryModel == null) categoryModel = new Model.CategoryModel();
            return View(categoryModel);
        }

        public JsonResult GetCategoryJson(int pCatid, int Level)
        {
            IServices.ICategoryServices categoryDal = new Services.CategoryServices();
            Model.CategoryParam param = new Model.CategoryParam();
            param.PageNo = 1;
            param.PageRow = 200;
            param.pCatid = pCatid;
            param.Level = Level;
            var CateList = categoryDal.Search(param);
            return Json(CateList, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 出版社
        public ActionResult PublisherList(int? p)
        {
            if (p == null) p = 0;
            IServices.IPublisherServices publisherDal = new Services.PublisherServices();
            ViewBag.publisherCount = publisherDal.GetCount(null);

            Model.PublisherParam param = new Model.PublisherParam();
            param.PageNo = Convert.ToInt32(p);
            param.PageRow = 10;
            var publisherList = publisherDal.Search(param);
            return View(publisherList);
        }

        public ActionResult PublisherEdit(int? ID, string Act, Model.PublisherModel model)
        {
            if (ID == null) ID = 0;
            IServices.IPublisherServices publisherDal = new Services.PublisherServices();

            if (Act == "E")
            {
                model.PublisherID = Convert.ToInt32(ID);
                if (!publisherDal.Exist(model.PublisherName))
                {
                    if (publisherDal.Modify(model))
                    {
                        ModelState.AddModelError("Info", "操作成功");
                    }
                    else
                    {
                        ModelState.AddModelError("Info", "操作失败请联系管理员");
                    }
                }
                else
                {
                    ModelState.AddModelError("Info", "出版社已经存在，请核查");
                }
            }
            else if (Act == "A")
            {
                if (!publisherDal.Exist(model.PublisherName))
                {
                    if (publisherDal.Add(model) != 0)
                    {
                        ModelState.AddModelError("Info", "操作成功");
                    }
                    else
                    {
                        ModelState.AddModelError("Info", "操作失败请联系管理员");
                    }
                }
                else
                {
                    ModelState.AddModelError("Info", "出版社已经存在，请核查");
                }
            }
            else if (Act == "D")
            {
                if (publisherDal.Delete(Convert.ToInt32(ID)))
                {
                    ModelState.AddModelError("Info", "操作成功");
                }
                else
                {
                    ModelState.AddModelError("Info", "操作失败请联系管理员");
                }
                return Redirect("/Admin/PublisherList");
            }

            var publisherModel = publisherDal.GetEntityById(Convert.ToInt32(ID));
            if (publisherModel == null) publisherModel = new Model.PublisherModel();
            return View(publisherModel);
        }
        #endregion

        #region 评论
        public ActionResult CommentList(int? p)
        {
            if (p == null) p = 0;
            IServices.ICommentServices commentDal = new Services.CommentServices();
            ViewBag.commentCount = commentDal.GetCount(null);

            Model.CommentParam param = new Model.CommentParam();
            param.PageNo = Convert.ToInt32(p);
            param.PageRow = 10;
            var commentList = commentDal.Search(param);
            return View(commentList);
        }

        public ActionResult CommentEdit(int? ID, string Act, Model.PublisherModel model)
        {
            if (ID == null) ID = 0;
            IServices.ICommentServices commentDal = new Services.CommentServices();

            if (Act == "D")
            {
                if (commentDal.Delete(Convert.ToInt32(ID)))
                {
                    ModelState.AddModelError("Info", "操作成功");
                }
                else
                {
                    ModelState.AddModelError("Info", "操作失败请联系管理员");
                }
                return Redirect("/Admin/CommentList");
            }

            var commentModel = commentDal.GetEntityById(Convert.ToInt32(ID));
            if (commentModel == null) commentModel = new Model.CommentModel();
            return View(commentModel);
        }
        #endregion

        #region 图书
        public ActionResult PrductList(int? p)
        {
            if (p == null) p = 0;
            IServices.IProductServices productDal = new Services.ProductServices();
            ViewBag.productCount = productDal.GetCount(null);

            Model.ProductParam param = new Model.ProductParam();
            param.PageNo = Convert.ToInt32(p);
            param.PageRow = 10;
            param.isSpecial = -1;
            var publisherList = productDal.Search(param);
            return View(publisherList);
        }

        public ActionResult ProductEdit(int? ID, string Act, Model.ProductModel model, FormCollection form)
        {
            if (ID == null) ID = 0;
            IServices.IProductServices productDal = new Services.ProductServices();
            IServices.ICategoryServices categoryDal = new Services.CategoryServices();
            IServices.IPublisherServices publisherDal = new Services.PublisherServices();

            if (Act == "U")
            {
                if (Request.Files.Count > 0)
                {
                    var file = Request.Files[0];
                    if (file.ContentLength > 0)
                    {
                        file.SaveAs(Server.MapPath(@"\ProductImg\" + ID + ".jpg"));
                        model.Image = "/ProductImg/" + ID + ".jpg";
                        model.BookID = Convert.ToInt32(ID);
                        productDal.ModifyImg(model);
                        ModelState.AddModelError("Info1", "封面修改成功");
                    }
                }
                else
                {
                    ModelState.AddModelError("Info1", "上传错误，请联系管理员");
                }
            }
            else if (Act == "E")
            {
                model.BookID = Convert.ToInt32(ID);
                if (productDal.Modify(model))
                {
                    ModelState.AddModelError("Info", "操作成功");
                }
                else
                {
                    ModelState.AddModelError("Info", "操作失败请联系管理员");
                }
            }
            else if (Act == "A")
            {
                int productID = productDal.Add(model);
                if (productID != 0)
                {
                    ModelState.AddModelError("Info", "操作成功");
                    return Redirect("/Admin/ProductEdit/" + productID);
                }
                else
                {
                    ModelState.AddModelError("Info", "操作失败请联系管理员");
                }
            }


            Model.CategoryParam param = new Model.CategoryParam();
            param.PageNo = 1;
            param.PageRow = 200;
            param.pCatid = 0;
            param.Level = 1;
            var firstCateList = categoryDal.Search(param);
            List<SelectListItem> Items = new List<SelectListItem>();
            foreach (var item in firstCateList)
            {
                Items.Add(new SelectListItem { Value = item.CategoryID.ToString(), Text = item.CategoryName });
            }
            ViewBag.firstCateList = Items;

            param.Level = 2;
            var CateList = categoryDal.Search(param);
            List<SelectListItem> Itemsr = new List<SelectListItem>();
            foreach (var item in CateList)
            {
                Itemsr.Add(new SelectListItem { Value = item.CategoryID.ToString(), Text = item.CategoryName });
            }
            ViewBag.CateList = Itemsr;

            var parampub = new Model.PublisherParam();
            parampub.PageNo = 1;
            parampub.PageRow = 2000;
            var publisherList = publisherDal.Search(parampub);
            List<SelectListItem> Itemsrs = new List<SelectListItem>();
            foreach (var item in publisherList)
            {
                Itemsrs.Add(new SelectListItem { Value = item.PublisherID.ToString(), Text = item.PublisherName });
            }
            ViewBag.publisherList = Itemsrs;

            var productModel = productDal.GetEntityById(Convert.ToInt32(ID));
            if (productModel == null) productModel = new Model.ProductModel();
            return View(productModel);
        }
        #endregion


    }
}
